# Copyright 2014-present PlatformIO <contact@platformio.org>
# Licensed under the Apache License, Version 2.0

"""
    Custom Builder for Luckfox Pico (ARM Linux uClibc)
    Toolchain: /srv/luckfox-pico/tools/linux/toolchain/arm-rockchip830-linux-uclibcgnueabihf
"""

from SCons.Script import COMMAND_LINE_TARGETS, AlwaysBuild, Default, DefaultEnvironment
import os

env = DefaultEnvironment()

# =============== 配置交叉工具链 ===============
TOOLCHAIN_ROOT = "/srv/luckfox-pico/tools/linux/toolchain/arm-rockchip830-linux-uclibcgnueabihf"
TOOLCHAIN_BIN = os.path.join(TOOLCHAIN_ROOT, "bin")
TOOLCHAIN_PREFIX = "arm-rockchip830-linux-uclibcgnueabihf-"

def toolchain_binary(name):
    return os.path.join(TOOLCHAIN_BIN, TOOLCHAIN_PREFIX + name)

# 检查工具链是否存在
gcc_path = toolchain_binary("gcc")
if not os.path.isfile(gcc_path):
    raise FileNotFoundError(f"Cross compiler not found: {gcc_path}")

# =============== 设置工具链 ===============
env.Replace(
    CC=toolchain_binary("gcc"),
    CXX=toolchain_binary("g++"),
    AR=toolchain_binary("ar"),
    AS=toolchain_binary("as"),
    LD=toolchain_binary("ld"),
    OBJCOPY=toolchain_binary("objcopy"),
    SIZE=toolchain_binary("size"),
    STRIP=toolchain_binary("strip"),
    RANLIB=toolchain_binary("ranlib"),
    NM=toolchain_binary("nm"),
)

# 可选：设置 sysroot（如果你有 rootfs）
SYSROOT = "/srv/luckfox-pico/sysdrv/source/buildroot/buildroot-2023.02.6/output/staging"
env.Append(CCFLAGS=[f"--sysroot={SYSROOT}"], LINKFLAGS=[f"--sysroot={SYSROOT}"])

# 强制静态链接（推荐用于 uClibc，避免目标设备缺少共享库）
#env.Append(LINKFLAGS=["-static"])

# =============== 保留用户定义的编译标志 ===============
# 注意：native 原始脚本会调用 env.Tool() 覆盖 flags，我们跳过它
# 所以直接保留原始 CFLAGS/CXXFLAGS 即可

#
# Target: Build executable program
#
target_bin = env.BuildProgram()

#
# Target: Execute binary (on host? not applicable for cross)
# We disable 'exec' and 'upload' or repurpose them
#

# Since this is cross-compilation, we cannot execute on host
# So we just print a message or skip
exec_action = env.VerboseAction(
    'echo "Binary compiled for Luckfox Pico: $SOURCE"',
    "Compiled for Luckfox Pico"
)
AlwaysBuild(env.Alias("exec", target_bin, exec_action))
AlwaysBuild(env.Alias("upload", target_bin, exec_action))

#
# Target: Print binary size
#
target_size = env.Alias("size", target_bin, env.VerboseAction(
    '"%s" -d $SOURCE' % toolchain_binary("size"),
    "Calculating size $SOURCE"
))
AlwaysBuild(target_size)

#
# Default targets
#
Default([target_bin])
